import json
import os
import re
from pathlib import Path

# 配置基础路径
ANGULAR_BASE = "/Users/justinzhang/WorkSpace/com.ein/project/南京/angularjs/platform-ui/html"
RUOYI_BASE = "/Users/justinzhang/WorkSpace/com.ein/demo/angularjs2vue3/RuoYi-Vue/ruoyi-ui/src/views"

def load_json_data(file_path):
    """加载JSON数据"""
    with open(file_path, 'r', encoding='utf-8') as f:
        return json.load(f)

def extract_controller_name(html_content):
    """从HTML内容中提取ng-controller名称"""
    pattern = r'(?:ng-controller|data-ng-controller)="([\w$]+)"'
    match = re.search(pattern, html_content)
    return match.group(1) if match else None

def find_function_code(js_content, function_name):
    """在JS内容中查找函数定义代码"""
    # 尝试匹配函数定义形式
    func_pattern = r'function\s+' + re.escape(function_name) + r'\s*\([^)]*\)\s*{'
    func_match = re.search(func_pattern, js_content)

    if func_match:
        # 找到函数开始位置
        start_index = func_match.start()

        # 查找函数结束位置
        brace_count = 1
        current_index = start_index + len(func_match.group(0))

        while brace_count > 0 and current_index < len(js_content):
            if js_content[current_index] == '{':
                brace_count += 1
            elif js_content[current_index] == '}':
                brace_count -= 1
            current_index += 1

        if brace_count == 0:
            # 返回整个函数代码
            return js_content[start_index:current_index]
        else:
            # 如果无法找到匹配的结束大括号，返回函数声明部分
            return func_match.group(0)

    return None

def process_menu_node(node, parent=None):
    """处理菜单节点并生成Vue文件"""
    # 处理当前节点
    if 'meta' in node and 'htmlUrl' in node['meta']:
        process_page(node, parent)

    # 处理子节点
    if 'children' in node:
        for child in node['children']:
            process_menu_node(child, node)

    # 处理subPages
    if 'meta' in node and 'subPages' in node['meta']:
        for sub_page in node['meta']['subPages']:
            process_sub_page(sub_page, node)

def process_page(node, parent=None):
    """处理主页面节点"""
    meta = node['meta']
    path = node['path']
    title = meta['title']

    print(f"\n处理页面: {title} ({path})")

    # 构建源文件路径
    html_path = Path(ANGULAR_BASE) / meta['htmlUrl']
    js_files = meta.get('fileJs', [])

    # 读取HTML内容
    if not html_path.exists():
        print(f"HTML文件不存在: {html_path}")
        return

    with open(html_path, 'r', encoding='utf-8') as f:
        html_content = f.read()

    # 提取控制器名称
    controller_name = extract_controller_name(html_content)
    if not controller_name:
        print(f"在 {html_path} 中未找到ng-controller")
        return

    print(f"从HTML中提取的控制器名称: {controller_name}")

    # 在JS文件中查找控制器代码
    controller_code = None
    for js_file in js_files:
        js_path = Path(ANGULAR_BASE) / js_file
        if not js_path.exists():
            print(f"JS文件不存在: {js_path}")
            continue

        print(f"在JS文件中查找控制器: {js_path}")
        with open(js_path, 'r', encoding='utf-8') as f:
            js_content = f.read()

        # 直接查找函数定义
        controller_code = find_function_code(js_content, controller_name)
        if controller_code:
            print(f"成功找到控制器函数代码: {controller_name}")
            # 输出函数代码片段
            print(f"函数代码片段: {controller_code[:200]}...")
            break

    if not controller_code:
        print(f"未找到控制器代码: {controller_name}")
        return

    # 构建目标Vue文件路径
    component_path = node['component']
    vue_path = Path(RUOYI_BASE) / f"{component_path}.vue"
    vue_path.parent.mkdir(parents=True, exist_ok=True)

    # 创建Vue文件
    vue_content = f"""<template>
{html_content}
</template>

<script>
{controller_code}
</script>
"""
    with open(vue_path, 'w', encoding='utf-8') as f:
        f.write(vue_content)
    print(f"已创建Vue文件: {vue_path}")

    # 在控制器代码中查找dialogService.page调用
    find_dialog_service_calls(controller_code, node)

def process_sub_page(sub_page, parent_node):
    """处理子页面"""
    print(f"\n处理子页面: {sub_page['title']} ({sub_page['path']})")

    # 构建源文件路径
    html_path = Path(ANGULAR_BASE) / sub_page['htmlUrl']
    js_files = sub_page.get('fileJs', [])

    # 读取HTML内容
    if not html_path.exists():
        print(f"HTML文件不存在: {html_path}")
        return

    with open(html_path, 'r', encoding='utf-8') as f:
        html_content = f.read()

    # 提取控制器名称
    controller_name = extract_controller_name(html_content)
    if not controller_name:
        print(f"在 {html_path} 中未找到ng-controller")
        return

    print(f"从HTML中提取的控制器名称: {controller_name}")

    # 在JS文件中查找控制器代码
    controller_code = None
    for js_file in js_files:
        js_path = Path(ANGULAR_BASE) / js_file
        if not js_path.exists():
            print(f"JS文件不存在: {js_path}")
            continue

        print(f"在JS文件中查找控制器: {js_path}")
        with open(js_path, 'r', encoding='utf-8') as f:
            js_content = f.read()

        # 直接查找函数定义
        controller_code = find_function_code(js_content, controller_name)
        if controller_code:
            print(f"成功找到控制器函数代码: {controller_name}")
            # 输出函数代码片段
            print(f"函数代码片段: {controller_code[:200]}...")
            break

    if not controller_code:
        print(f"未找到控制器代码: {controller_name}")
        return

    # 构建目标Vue文件路径
    parent_component = parent_node['component']
    html_filename = os.path.splitext(os.path.basename(sub_page['htmlUrl']))[0]
    vue_dir = Path(RUOYI_BASE) / os.path.dirname(parent_component) / 'dlg'
    vue_path = vue_dir / f"{html_filename}.vue"
    vue_dir.mkdir(parents=True, exist_ok=True)

    # 创建Vue文件
    vue_content = f"""<template>
{html_content}
</template>

<script>
{controller_code}
</script>
"""
    with open(vue_path, 'w', encoding='utf-8') as f:
        f.write(vue_content)
    print(f"已创建子页面Vue文件: {vue_path}")

def find_dialog_service_calls(js_content, node):
    """在JS代码中查找dialogService.page调用"""
    pattern = r'dialogService\.page\s*\(\s*["\']([^"\']+)["\']'
    matches = re.findall(pattern, js_content)

    if matches:
        print(f"在控制器代码中找到 dialogService.page 调用: {matches}")

    for alias in matches:
        # 在subPages中查找匹配的alias
        if 'meta' in node and 'subPages' in node['meta']:
            for sub_page in node['meta']['subPages']:
                if sub_page.get('alias') == alias:
                    print(f"找到匹配的 subPage (alias={alias}): {sub_page['title']}")
                    process_sub_page(sub_page, node)
                    break
            else:
                print(f"未找到匹配的 subPage (alias={alias})")

def main():
    # 加载JSON数据
    data = load_json_data('data.json')

    # 遍历所有菜单节点
    for menu in data:
        process_menu_node(menu)

if __name__ == "__main__":
    main()
